package com.demo.test;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.context.ContextUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

public class Demo1 {

	public static void main(String[] args) throws BlockException {
		String resourceName = "nodeA";
		initFlowQpsRule(resourceName);

		// 创建一个名称为entrance1，来源为appA 的上下文Context，同一个线程里不管执行多少次，返回的都是第一次创建的context
		ContextUtil.enter("entrance1", "appA");

		// 创建一个资源名称nodeA的Entry
		Entry nodeA = SphU.entry(resourceName);
		if (nodeA != null) {
			nodeA.exit();
		}

		// 清除上下文
		ContextUtil.exit();
	}

	private static void initFlowQpsRule(String resourceName) {
	    List<FlowRule> rules = new ArrayList<>();
	    FlowRule rule = new FlowRule(resourceName);
	    // set limit qps to 20
	    rule.setCount(20);
	    rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
	    //rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
	    //rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_RATE_LIMITER);
	    rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_WARM_UP);
	    rule.setLimitApp("default");
	    rules.add(rule);
	    // 加载流控规则
	    FlowRuleManager.loadRules(rules);
	}

}
